<template>
    <Modal @on-ok="choose" class="duty"
            title="选择职能"
            ok-text="保存"
            width="500"
            v-model="show"
            :mask-closable="false"
            :transfer="false">
        <Tree ref="tree" :data="dutyTree" show-checkbox style="height: 600px;overflow-y: scroll"></Tree>
    </Modal>
</template>

<script>
    import * as dutyOpr from '../../http/duty.api'
    export default {
        props: ['showModal'],
        name: "ChooseDuty",
        data() {
            return {
                show: false, // 控制当前模块显示关闭

                dutyTree: [],
            }
        },
        watch: {
            show: function (newVal, oldVal) { // 控制当前模块是否显示
                this.$emit('toggleDutyModal', newVal);
            },
            showModal: function (newVal, oldVal) { // 属性，外部接收过来
                this.show = newVal;
            },
        },
        mounted() {
            // console.log('mounted', this.showModal);
            //  console.log('mounted');
            this.getDutyList(); // 初始化组织架构树
        },
        created() {
            // console.log('created');
        },
        methods: {
            choose() { // 模态框确定
                const _this  = this;
                const nodes = _this.$refs.tree.getCheckedNodes();
                // console.log(nodes);
                _this.$emit('dutySelected', nodes);
            },

            getDutyList() { // 获取所有组织架构
                const _this = this;
                dutyOpr.getDutyList().then(function (res) {
                    // console.log(res)
                    let rootNode = res.data.rows.find(item => item.id === 1); // 找根节点，可能调整
                    let groupsObj = res.data.rows.reduce(function (groups, item) {
                        let val = ('' + item['parentId']).toUpperCase();
                        groups[val] = groups[val] || [];
                        groups[val].push(item);
                        return groups;
                    }, {});

                    function buildTree(node) {
                        let obj = {
                            title: node.funcName,
                            expand: true,
                            origin: node
                        };
                        if (groupsObj[node.id]) { // 有下级节点
                            // 设置子节点，进行监听
                            _this.$set(obj, 'children', groupsObj[node.id].filter(item => item.id !== 1).map(item => buildTree(item)));
                        }
                        return obj;
                    }
                    if (rootNode) {
                        _this.dutyTree = [buildTree(rootNode)];
                    }
                }).catch(function () {
                    console.log(arguments);
                });
            }
        }
     }
</script>

<style scoped>

</style>
